package com.meizu.llp.cameratest;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Camera mCamera;
    private CameraPreview cameraPreview;
    private LinearLayout frameLayout;
    private Button btn_capture;
    private Button btn_change_camera;
    private Button btn_change_flash;
    private Context context;

    private Consts.CameraType cameraType = Consts.CameraType.CAMERA_BACK;
    private Consts.FlashMode flashMode = Consts.FlashMode.FLASH_OFF;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        context = this;

        initCamera();
        cameraPreview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mCamera.autoFocus(new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean b, Camera camera) {
                        if (b){
                            System.out.println("success");
                        }else {
                            System.out.println("failed");
                        }
                    }
                });
                return false;
            }
        });

        frameLayout = (LinearLayout) findViewById(R.id.surfacelayout);
        frameLayout.addView(cameraPreview);

        btn_capture = (Button) findViewById(R.id.btn_capture);
        btn_capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCamera.takePicture(null, null,takePicture);
            }
        });

        btn_change_camera = (Button) findViewById(R.id.btn_change_camera);
        btn_change_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraType = cameraType== Consts.CameraType.CAMERA_BACK?Consts.CameraType.CAMERA_FRONT:Consts.CameraType.CAMERA_BACK;
                //关闭相机预览并重新启动
                restartCameraPreview();
                if (cameraType== Consts.CameraType.CAMERA_FRONT){
                    btn_change_flash.setVisibility(View.GONE);
                }else {
                    btn_change_flash.setVisibility(View.VISIBLE);
                }
            }
        });

        btn_change_flash = (Button) findViewById(R.id.btn_change_flash);
        btn_change_flash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("选择闪光灯属性");
                builder.setItems(new String[]{"关", "开", "自动"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i){
                            case 0:
                                flashMode = Consts.FlashMode.FLASH_OFF;
                                break;
                            case 1:
                                flashMode = Consts.FlashMode.FLASH_ON;
                                break;
                            case 2:
                                flashMode = Consts.FlashMode.FLASH_AUTO;
                                break;
                        }
                        //适配到parameter上
                        if (mCamera!=null) {
                            CameraUtil.setFlashModeInBackCamera(mCamera,cameraType,flashMode);
                        }
                        System.out.println("click button"+i);
                    }
                });
                builder.show();
            }
        });

    }

    private Camera.PictureCallback takePicture = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
            //when this method is finished, it will call stopPreview()
                try {
                    File imageFile = CameraUtil.getOutputImageFile();
                    String imageFilePath = imageFile.getAbsolutePath();
                    FileOutputStream fops = new FileOutputStream(imageFile);
                    fops.write(bytes);
                    fops.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //再次调用startPreview  to take more picture
            mCamera.startPreview();
        }
    };

    private void initCamera() {
        if (!CameraUtil.checkCameraHardware(context)) {
            return;
        }
        switch (cameraType){
            case CAMERA_BACK:
                mCamera = CameraUtil.getCameraInstance(
                        CameraUtil.findFacingCameraId(cameraType)
                );
                CameraUtil.setBackCameraParameters(mCamera);
                break;
            case CAMERA_FRONT:
                mCamera = CameraUtil.getCameraInstance(
                        CameraUtil.findFacingCameraId(cameraType)
                );
                CameraUtil.setFrontCameraParameters(mCamera);
                break;
        }
        cameraPreview = new CameraPreview(context, mCamera);
    }


    private void restartCameraPreview(){
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
        mCamera = CameraUtil.getCameraInstance(
                CameraUtil.findFacingCameraId(cameraType)
        );
        if (cameraPreview!=null) {
            SurfaceHolder holder = cameraPreview.getSurfaceHolder();
            if (holder!=null){
                try {
                    mCamera.setPreviewDisplay(holder);
                    System.out.println("set holder success");
                } catch (IOException e) {
                }
            }
        }
        if (cameraType==Consts.CameraType.CAMERA_BACK){
            CameraUtil.setBackCameraParameters(mCamera);
        }else {
            CameraUtil.setFrontCameraParameters(mCamera);
        }
        mCamera.startPreview();
        System.out.println("click the change");
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera==null){
            initCamera();
        }
        System.out.println("onResume");
    }

    @Override
    protected void onPause() {
        System.out.println("onPause");
        super.onPause();
        if (mCamera!=null){
            mCamera.stopPreview();
            mCamera.release();
            cameraPreview=null;
        }
    }

    @Override
    protected void onDestroy() {
        System.out.println("onDestroy");
        if (mCamera!=null) {
            mCamera.release();
            cameraPreview=null;
        }
        super.onDestroy();
    }
}
